export interface IConnectOpt {
  dbName: string // *数据库名称
  version: number // 数据库版本号（默认为当前时间戳）
}

export class ConnectDB {
  public db!: IDBDatabase
  public dbReq: IDBOpenDBRequest

  constructor(opt: IConnectOpt) {
    this.dbReq! = window.indexedDB.open(opt.dbName, opt.version)
  }

  /** 打开连接 */
  protected async connect() {
    return new Promise<IDBDatabase>((resolve, reject) => {
      this.dbReq.onsuccess = (evn: any) => {
        console.log('onsuccess')

        if (!this.db) {
          this.setup(evn.target.result)
        }
        resolve(this.db)
      }
      this.dbReq!.onerror = (evn: Event) => {
        reject({ flag: false, evn })
      }

      // 新建数据库
      this.dbReq.onupgradeneeded = (evn: any) => {
        console.log('onupgradeneeded')

        if (evn.target.result) {
          this.setup(evn.target.result)

          resolve(this.db)
        }
      }
    })
  }

  protected setup(db: IDBDatabase) {
    if (this.db) return

    this.db = db

    this.db.onabort = this.onabort
    this.db.onclose = this.onclose
    this.db.onerror = this.onerror
    this.db.onversionchange = this.onversionchange
  }

  protected onabort(evn: Event) {
    console.log('abort', evn)
  }
  protected onerror(evn: Event) {
    console.log('onerror', evn)
  }
  protected onclose(evn: Event) {
    console.log('onclose', evn)
  }
  protected onversionchange(evn: IDBVersionChangeEvent) {
    console.log('onversionchange', evn)
  }
}
